import React from 'react';
import { Layout, Menu, Dropdown, Avatar, Badge, Space } from 'antd';
import { 
  BellOutlined, 
  UserOutlined, 
  LogoutOutlined,
  SettingOutlined
} from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import { useUser } from '../contexts/UserContext';

const { Header } = Layout;

const AppHeader = () => {
  const history = useHistory();
  const { user, logout } = useUser();

  const handleMenuClick = (e) => {
    if (e.key === 'logout') {
      // 使用用户上下文的logout方法
      logout();
      // 跳转到登录页
      history.push('/login');
    } else if (e.key === 'profile') {
      history.push('/profile');
    } else if (e.key === 'settings') {
      history.push('/settings');
    }
  };

  const menu = (
    <Menu onClick={handleMenuClick}>
      <Menu.Item key="profile" icon={<UserOutlined />}>
        个人中心
      </Menu.Item>
      <Menu.Item key="settings" icon={<SettingOutlined />}>
        系统设置
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout" icon={<LogoutOutlined />}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <Header className="site-layout-background" style={{ padding: 0 }}>
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        padding: '0 24px'
      }}>
        <div style={{ fontSize: '20px', fontWeight: 'bold', color: 'white' }}>
          问题跟踪系统
        </div>
        <Space>
          <Badge count={5}>
            <BellOutlined style={{ fontSize: '20px', color: 'white' }} />
          </Badge>
          <Dropdown overlay={menu} placement="bottomRight">
            <div style={{ display: 'flex', alignItems: 'center', cursor: 'pointer', color: 'white' }}>
              <Avatar 
                style={{ backgroundColor: '#1890ff', marginRight: '8px' }} 
                icon={<UserOutlined />}
                onError={() => {
                  console.log('头像加载失败，使用默认头像');
                  return true; // 返回true使用fallback icon
                }}
              />
              <span style={{ fontSize: '14px' }}>
                {user?.username || '用户'}
              </span>
            </div>
          </Dropdown>
        </Space>
      </div>
    </Header>
  );
};

export default AppHeader;